/*
 *     LoginFilter.java  Copyright (c) 2021. cc01cc. All rights reserved.
 *
 *     This file is part of e-commerce.
 *
 *     e-commerce is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published
 *     by the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     e-commerce is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package filter;

import util.Constant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

//@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})

public class LoginFilter  implements Filter {
    @Override
    public void destroy(){
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException{
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        String request_uri = req.getRequestURI();
        String ctxPath = req.getContextPath();
        String uri = request_uri.substring(ctxPath.length());

        if(uri.contains("login.jsp")||uri.contains("loginServlet")||uri.contains("loginCheck")){
            chain.doFilter(request, response);
        }else{
            if(null != session.getAttribute(Constant.USER_SESSION) || null != session.getAttribute(Constant.MANAGER_SESSION)){
                chain.doFilter(request, response);
            }else{
                out.println("请先登录！返回登录注册页");
                resp.setHeader("refresh", "3;url =" + ctxPath + "/login.jsp");
            }
        }
    }
    @Override
    public void init(FilterConfig fConfig) throws ServletException{

    }
}
